package com.small.sentinel.slots.block.degrade;

import com.small.common.core.util.StringUtil;
import com.small.sentinel.slots.block.RuleConstant;
import com.small.sentinel.slots.block.degrade.circuitbreaker.CircuitBreaker;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 *断路规则的规则管理器
 */
public class DegradeRuleManager {

    private static volatile Map<String, List<CircuitBreaker>> circuitBreakers = new HashMap<>();

    static List<CircuitBreaker> getCircuitBreakers(String resourceName) {
        return circuitBreakers.get(resourceName);
    }

    /**
     * 校验规则
     * @param rule
     * @return
     */
    public static boolean isValidRule(DegradeRule rule) {
        boolean baseValid = rule != null && !StringUtil.isBlank(rule.getResource())
                && rule.getCount() >= 0 && rule.getTimeWindow() > 0;
        if (!baseValid) {
            return false;
        }
        if (rule.getMinRequestAmount() <= 0 || rule.getStatIntervalMs() <= 0) {
            return false;
        }
        switch (rule.getGrade()) {
            case RuleConstant.DEGRADE_GRADE_RT:
                return rule.getSlowRatioThreshold() >= 0 && rule.getSlowRatioThreshold() <= 1;
            case RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO:
                return rule.getCount() <= 1;
            case RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT:
                return true;
            default:
                return false;
        }
    }
}
